package com.outeng.nfcActivity;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

//import com.google.android.gms.common.api.GoogleApiClient;




import java.io.IOException;

import com.example.tgls.R;

/**
 * NFC读写（暂时不用）
 * Created by lgl on 16/3/1.
 */
public class MainSActivity extends AppCompatActivity {

    private Button btn_list;
    //选中的包名
    private String mPackNmae;
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;

//    private GoogleApiClient client;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_list = (Button) findViewById(R.id.btn_list);
        //初始化NfcAdapter
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        //初始化PendingIntent
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);


        //点击跳转
        btn_list = (Button) findViewById(R.id.btn_list);
        btn_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainSActivity.this,ListActivity.class);
                startActivityForResult(intent,1);
            }
        });

    }
    
    /**
     * Android2.3.3版本以后可以下代码检测NFC是否开启
     * @param context
     * @return
     */
    public static boolean hasNfc(Context context){  
        boolean bRet=false;  
        if(context==null)  
            return bRet;  
        NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);  
        NfcAdapter adapter = manager.getDefaultAdapter();  
        if (adapter != null && adapter.isEnabled()) {  
            // adapter存在，能启用  
            bRet=true;  
        }  
        return bRet;  
    }  
    
    

    //当设置android:launchMode="singleTop"时调用
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //没有选择的话就不执行操作了
        if (mPackNmae == null) {
            return;
        }

        //1.获取Tag对象
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //写入程序
        writeNFC(tag);


    }

    //NFC写入
    private void writeNFC(Tag tag) {
        //null不执行操作，强调写程序的逻辑性
        if (tag == null) {
            return;
        }

        NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{NdefRecord.createApplicationRecord(mPackNmae)});
        //获得写入大小
        int size = ndefMessage.toByteArray().length;
        //2.判断是否是NDEF标签
            try {
                Ndef ndef = Ndef.get(tag);
                if(ndef != null) {
                    //说明是NDEF标签,开始连接
                    ndef.connect();
                    //判断是否可写
                    if(!ndef.isWritable()){
                        Toast.makeText(this, "当前设备不支持写入",Toast.LENGTH_LONG).show();
                        return;
                    }
                    //判断大小
                    if(ndef.getMaxSize() < size){
                        Toast.makeText(this, "容量太小了",Toast.LENGTH_LONG).show();
                        return;
                    }
                    //写入
                    try {
                        ndef.writeNdefMessage(ndefMessage);
                        Toast.makeText(this, "写入成功",Toast.LENGTH_LONG).show();
                    } catch (FormatException e) {
                        e.printStackTrace();
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();

        }
    }

    //使当前窗口置顶，权限高于三重过滤
    @Override
    protected void onResume() {
        super.onResume();

        if (mNfcAdapter != null) {
            //设置当前activity为栈顶
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //恢复栈
        if (mNfcAdapter != null) {
            mNfcAdapter.disableForegroundDispatch(this);
        }
    }

}
